package cn.mesmile.es.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.mesmile.es.common.R;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author zb
 * @date 2021/6/13 17:19
 * @Description:
 */
@RestController
@RequestMapping("/api/v1/dic")
public class DicController {

    // 注意字典，每行只能放一个词语，并且字典文件编码格式为 UTF-8
    // 这里将字典文件dic.txt放在 resources下的 static 文件夹下面

    @GetMapping("/getAll")
    public R getAll(HttpServletRequest request) {
//        String realPath = request.getServletContext().getRealPath("/");
//        System.out.println("realPath = " + realPath);
        // 获取resource下路径
        String filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("static/dic.txt")).getPath();
        // 读取文件
        List<String> strings = FileUtil.readUtf8Lines(filePath);
        // 过滤空行
        CollectionUtil.removeEmpty(strings);
        return R.data(strings);
    }

    @GetMapping("/delete")
    public R delete(@RequestParam("keyword")String keyword) {
        Assert.isTrue(StrUtil.isNotEmpty(keyword), "关键字不允许为空");
        // 获取resource下路径
        String filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("static/dic.txt")).getPath();
        // 读取文件
        List<String> wordList = FileUtil.readUtf8Lines(filePath);
        // 移除关键字
        List<String> newWordList = CollectionUtil.removeAny(wordList, keyword,"",null);
        // 重写回去
        FileUtil.writeUtf8Lines(newWordList, filePath);
        return R.status(true);
    }

    @GetMapping("/add")
    public R add(@RequestParam("keyword")String keyword){
        Assert.isTrue(StrUtil.isNotEmpty(keyword), "关键字不允许为空");
        // 获取路径
        String filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("static/dic.txt")).getPath();
        // 添加行
        List<String> keywordList = Collections.singletonList(keyword);
        // 追加方式添加
        FileUtil.writeLines(keywordList, filePath, StandardCharsets.UTF_8, true);
        return R.status(true);
    }

}
